#region using

using System;
using System.Text;
using System.Web;
using BlogEngine.Core;
using BlogEngine.Core.Web.Controls;

#endregion

/// <summary>
/// Adds an Odiogo 'Listen' image button to the top of all posts.
/// </summary>
[Extension("Adds an Odiogo 'Listen' image button to the top of all posts", "1.1", "Mads Kristensen")]
public class Odiogo
{
	static protected ExtensionSettings _settings = null;

	static protected int OdigoFeedId
	{
		get
		{
			int feedid = 0;
			Int32.TryParse(_settings.GetSingleValue("feedID"), out feedid);
			return feedid;
		}
	}

	/// <summary>
	/// Initializes a new instance of the <see cref="Odiogo"/> class.
	/// </summary>
	public Odiogo()
	{
		Post.Serving += new EventHandler<ServingEventArgs>(Post_Serving);

		ExtensionSettings settings = new ExtensionSettings("Odiogo");
		settings.AddParameter("feedID", "Odiogo Feed ID", 10, true);
		settings.IsScalar = true;

		ExtensionManager.ImportSettings(settings);
		_settings = ExtensionManager.GetSettings("Odiogo");
	}

	/// <summary>
	/// Handles the Serving event of the Post object.
	/// </summary>
	void Post_Serving(object sender, ServingEventArgs e)
	{
		if (e.Location == ServingLocation.PostList || e.Location == ServingLocation.SinglePost)
		{
			Post post = (Post)sender;
			string script = string.Format(SCRIPT, OdigoFeedId, post.Title.Replace("'", "\\'"), post.Id.ToString());
			e.Body = script + e.Body;

			AddOdiogoScript();
		}
	}

	/// <summary>
	/// Adds the odiogo script to the page header.
	/// </summary>
	private static void AddOdiogoScript()
	{
		HttpContext context = HttpContext.Current;
		if (context.CurrentHandler is System.Web.UI.Page)
			// Make sure we haven't already added the script to the page header.
			if (context.Items["odiogo"] == null)
			{
				System.Web.UI.Page page = (System.Web.UI.Page)context.CurrentHandler;
				string js = string.Format("<script type=\"text/javascript\" src=\"http://podcasts.odiogo.com/odiogo_js.php?feed_id={0}&platform=be\"></script>", OdigoFeedId);
				page.Header.Controls.Add(new System.Web.UI.LiteralControl(js));
				context.Items["odiogo"] = 1;
			}
	}

	private static readonly string SCRIPT = CreateScript();

	/// <summary>
	/// Creates the script used to display the image button.
	/// </summary>
	private static string CreateScript()
	{
		StringBuilder sb = new StringBuilder();
		sb.AppendLine("<div class=\"odiogo\">");
		sb.AppendLine("<script type=\"text/javascript\">");
		sb.AppendLine("<!--");
		sb.AppendLine("showOdiogoReadNowButton ('{0}', '{1}', '{2}', 290, 55);");
		sb.AppendLine("//-->");
		sb.AppendLine("</script><br />");
		sb.AppendLine("<script type=\"text/javascript\">");
		sb.AppendLine("showInitialOdiogoReadNowFrame ('{0}', '{2}', 290, 0);");
		sb.AppendLine("//-->");
		sb.AppendLine("</script>");
		sb.AppendLine("</div>");

		return sb.ToString();
	}

}